package com.wqj.kyee.gps.bluetooth.server

import android.bluetooth.BluetoothSocket
import android.bluetooth.BluetoothServerSocket
import android.os.Handler
import android.os.Message
import com.wqj.kyee.gps.bluetooth.BtDevicesActivity
import java.io.IOException
import java.util.*


/**
 * Created by kyee on 17-12-8.
 */
public class BtServerThread(mHandler: Handler) : Thread() {
    private val mmServerSocket: BluetoothServerSocket?
    private var mHandler: Handler
    init {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        var tmp: BluetoothServerSocket? = null
        val uuid = UUID.fromString(BtDevicesActivity.BT_UUID)
        this.mHandler = mHandler
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = BtDevicesActivity.bluetoothAdapter
                    .listenUsingRfcommWithServiceRecord(BtDevicesActivity.BT_SERVER_NAME, uuid)
        } catch (e: IOException) {
        }
        mmServerSocket = tmp
    }

    override fun run() {
        var socket: BluetoothSocket?
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket!!.accept()
            } catch (e: IOException) {
                val msg = Message.obtain()
                msg.what = BtDevicesActivity.BT_SERVER_CONNECT_FAIL
                mHandler.sendMessage(msg)
                break
            }

            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                // manageConnectedSocket(socket)
                BtDevicesActivity.connectedSock = socket
                val msg = Message.obtain()
                msg.what = BtDevicesActivity.BT_SERVER_CONNECT_SUCCESS
                mHandler.sendMessage(msg)
                mmServerSocket.close()
                break
            }
        }
    }

    /** Will cancel the listening socket, and cause the thread to finish  */
    fun cancel() {
        try {
            mmServerSocket!!.close()
        } catch (e: IOException) {
        }

    }
}